﻿//https://leetcode.cn/problems/merge-intervals/?envType=study-plan-v2&envId=top-100-liked

class Solution {
public:
    vector<vector<int>> merge(vector<vector<int>>& intervals)
    {
        //按照左区间排序
        sort(intervals.begin(), intervals.end());
        int left = intervals[0][0], right = intervals[0][1];
        int n = intervals.size();
        vector<vector<int>> ret;

        for (int i = 1; i < n; i++)
        {
            int a = intervals[i][0], b = intervals[i][1];
            if (a <= right)
            {
                //存在重叠部分
                right = max(right, b);
            }
            else
            {
                //无重叠部分
                ret.push_back({ left,right });
                right = b;
                left = a;
            }
        }

        //最后合并完成的区间加入结果
        ret.push_back({ left,right });
        return ret;

    }
};